package web.servlet;

import com.alibaba.fastjson.JSONObject;
import com.rdc.example.bean.PageBean;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.SongDTO;
import com.rdc.example.bean.dto.UserDTO;
import com.rdc.example.dao.PlayCountDao;
import com.rdc.example.dao.impl.PlayCountDaoImpl;
import com.rdc.example.service.PlayCountService;
import com.rdc.example.service.SongLikesService;
import com.rdc.example.service.SongService;
import com.rdc.example.service.impl.PlayCountServiceImpl;
import com.rdc.example.service.impl.SongLikesServiceImpl;
import com.rdc.example.service.impl.SongServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/song/*")
@MultipartConfig
public class SongServlet extends BaseServlet{

    SongService songService = new SongServiceImpl();
    SongLikesService songLikesService=new SongLikesServiceImpl();
    PlayCountService playCountService=new PlayCountServiceImpl();

    public void addSong(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("addSong...");

        //获取信息
        resp.setContentType("application/json;charset=utf-8");
        //创建DiskFileItemFactory工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置文件缓存目录，如果该文件夹不存在则创建一个
        File file = new File("D:\\TempFolder");
        if (!file.exists()) {
            file.mkdirs();
        }
        factory.setRepository(file);
        //创建ServletFileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置字符编码
        fileUpload.setHeaderEncoding("utf-8");
        //解析request，获取FileItem对象
        List<FileItem> fileItems = fileUpload.parseRequest(req);
        //获取信息 使用map储存,再读出来
        Map<String, String> formFields = new HashMap<>();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                formFields.put(item.getFieldName(), item.getString("UTF-8"));
            }
        }//map中读取数据
        SongDTO songDTO = new SongDTO();
        songDTO.setName(formFields.get("name"));

        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();

        songDTO.setUserId(userId);
        Result result = songService.insertSong(songDTO,fileItems);
        System.out.println(result);

        //返回结果
        resp.getWriter().write(JSONObject.toJSONString(result));
    }

    public void getSong(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("getSong...");

        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();

        Result result=songService.getSongListByUserId(userId);
        //返回结果

        List<SongDTO> songDTOList= (List<SongDTO>) result.getData();
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(songDTOList));

    }
    public void getSongsByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("getSongListByUserId...");
        //PageBean<SongDTO> getSongListByUserId(Integer userId, Integer pageBegin, Integer pageSize)
        //接收 当前页码 和 每页展示条数  eg: url?currentPage=1&pageSize=5
        int currentPage = Integer.parseInt(req.getParameter("currentPage"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        PageBean<SongDTO> pageBean= songService.getSongListByUserId(userId,currentPage,pageSize);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(pageBean));
    }

    public void deleteSong(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("deleteSongId...");
        //前端获取songId
        int songId = Integer.parseInt(req.getParameter("songId"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        Result result=songService.deleteSongById(songId,userId);
        //返回结果
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(result));

    }

    public void songLike(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("songLike...");
        //前端获取songId
        int songId = Integer.parseInt(req.getParameter("songId"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        Result result=songLikesService.turnSongLike(userId,songId);
        //返回结果
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(result));

    }

    public void addPlayCount(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("addPlayCount...");
        //前端获取songId
        int songId = Integer.parseInt(req.getParameter("songId"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        Result result=playCountService.addPlayCount(userId,songId);
        //返回结果
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(result));
    }

}
